<?php
/**
 +----------------------------------------------------------
 * 订单发票管理
 +----------------------------------------------------------
 * Author: ExBOY
 * Time: 2014-03-18 $ 2016-06-03 更新 wangjianjun
 * [Ecos!] (C)2003-2014 Shopex Inc.
 +----------------------------------------------------------
 */
class invoice_ctl_admin_order extends desktop_controller{
    
    function index(){
    	$this->title = '订单发票列表';
        $params = array('title'=>$this->title,
                        'use_buildin_set_tag'=>true,
                        'use_buildin_filter'=>true,
                        'use_buildin_export'=>true,
                        'use_buildin_import'=>false,
                        'use_buildin_recycle'=>false,
        );
        $this->finder('invoice_mdl_order', $params);
    }

    //-- 分类导航
    function _views(){
        $mdl_order = $this->app->model('order');
        $sub_menu = array(
            0 => array('label'=>__('全部'),'filter'=>$base_filter),
            1 => array('label'=>__('纸质'),'filter'=>array('mode'=>'0'),'optional'=>false),
            2 => array('label'=>__('电子'),'filter'=>array('mode'=>'1'),'optional'=>false),
            3 => array('label'=>__('已开票'),'filter'=>array('is_status'=>'1'),'optional'=>false),
            4 => array('label'=>__('未开票'),'filter'=>array('is_status'=>'0'),'optional'=>false),
        );
        
        $i=0;
        foreach($sub_menu as $k => $v){
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->viewcount($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=invoice&ctl='.$_GET['ctl'].'&act=index&view='.$i++;
        }
        return $sub_menu;
    }
    
    //作废
    function doCancel(){
        $url = 'javascript:finderGroup["'.$_GET['finder_id'].'"].refresh();';  
        $id = $_GET["id"];
        $order_id = $_GET["order_id"];
        if(!$id || !$order_id){
            $this->splash('error',$url,'操作出错，不存在此条发票记录，请重新操作。');
        }
        $arr_cancel = array(
            "id" => $id,
            "order_id" => $order_id,
        );
        $result = kernel::single('invoice_process')->cancel($arr_cancel,"invoice_list");
        if($result){
            if(intval($result["mode"]) == 1){
                //这里提示打开电子发票接口是否缺少必要参数
                if(!empty($result["arr_hint"])){
                    $this->end(false,"电子发票冲红失败：".implode("，", $result["arr_hint"])."。");
                }else{
                    $hint = "电子发票冲红操作已执行。";
                }
            }else{
                $hint = "作废纸质发票成功。";//纸质发票
            }
            $this->splash('success',$url,$hint);
        }else{
            $this->splash('error',$url,'作废发票失败。');
        }
    }
    
    //开票
    function doBilling(){
        $url = 'javascript:finderGroup["'.$_GET['finder_id'].'"].refresh();';
        $id = $_GET["id"];
        $order_id = $_GET["order_id"];
        if(!$id || !$order_id){
            $this->splash('error',$url,'操作出错，不存在此条发票记录，请重新操作。');
        }
        $arr_billing = array(
            "id" => $id,
            "order_id" => $order_id,
        );
        $result = kernel::single('invoice_process')->billing($arr_billing);
        if($result){
            if(intval($result["mode"]) == 1){
                //这里提示打开电子发票接口是否缺少必要参数
                if(!empty($result["arr_hint"])){
                    $this->splash('error',$url,"电子发票开蓝票失败：".implode("，", $result["arr_hint"])."。");
                }else{
                    $hint = "电子发票开蓝票操作已执行。";
                }
            }else{
                $hint = "纸质发票开票成功。";//纸质发票
            }
            $this->splash('success',$url,$hint);
        }else{
            $this->splash('error',$url,'开票失败。');
        }
    }
    
    //编辑页面展示
    function edit(){
        $id = intval($_GET["id"]);
        if(!$id){
            return false;
        }
        
        //获取发票信息
        $mdlInOrder = app::get('invoice')->model('order');
        $rs_invoice_order = $mdlInOrder->dump(array("id"=>$id),"*");
        $this->pagedata["invoice_order"] = $rs_invoice_order;
        
        //获取订单信息
        $mdlOmeOrders = app::get('ome')->model('orders');
        $rs_ome_orders = $mdlOmeOrders->dump(array("order_id"=>$rs_invoice_order["order_id"]));
        $this->pagedata["ome_orders"] = $rs_ome_orders;
        
        //获取发票内容
        $mdlInContent = app::get('invoice')->model('content');
        $this->pagedata["invoice_content"] = $mdlInContent->getList();
        
        $this->pagedata["act"] = "doEdit";
        
        $this->page('admin/order_editor.html');
    }
    
    //编辑提交操作
    function doEdit(){
        $this->begin();
        
        $id = $_POST["item"]["id"];
        if(!$id){
            return false;
        }
        
        $check_result = kernel::single('invoice_check')->checkEdit($id);
        if(!$check_result){
            $this->end(false, '编辑失败，此发票记录必须是未开票状态。');
        }
        
        $result = kernel::single('invoice_process')->edit($_POST["item"]);
        if($result){
            $this->end(true, '编辑发票信息成功。');
        }else{
            $this->end(false, '编辑发票信息失败。');
        }
    }
    
    //新建发票信息发票页面展示
    function addNewSame(){
        $id = intval($_GET["id"]);
        if(!$id){
            return false;
        }
        
        //获取发票信息
        $mdlInOrder = app::get('invoice')->model('order');
        $rs_invoice_order = $mdlInOrder->dump(array("id"=>$id),"*");
        $this->pagedata["invoice_order"] = $rs_invoice_order;
        
        //获取订单信息
        $mdlOmeOrders = app::get('ome')->model('orders');
        $rs_ome_orders = $mdlOmeOrders->dump(array("order_id"=>$rs_invoice_order["order_id"]));
        $this->pagedata["ome_orders"] = $rs_ome_orders;
        
        //获取发票内容
        $mdlInContent = app::get('invoice')->model('content');
        $this->pagedata["invoice_content"] = $mdlInContent->getList();
        
        $this->pagedata["act"] = "doAddNewSame";
        
        $this->page('admin/order_editor.html');
    }
    
    //新建发票信息提交操作
    function doAddNewSame(){
        $this->begin();
        $id = $_POST["item"]["id"];
        $order_id = $_POST["item"]["order_id"];
        if(!$id || !$order_id){
            return false;
        }
        
        $result = kernel::single('invoice_process')->create($_POST["item"],"invoice_list_add_same");
        
        if($result){
            $this->end(true, '新建类似发票信息成功。');
        }else{
            $this->end(false, '新建类似发票信息失败。');
        }
    }
    
    //预览电子发票
    function preview(){
        if(!$_GET["id"] || !$_GET["type"]){
            echo '<script>window.close();</script>';
            return;
        }
        $mdlInOrder = app::get('invoice')->model('order');
        $rs_invoice = $mdlInOrder->dump(array("id"=>$_GET["id"]));
        $einvoice_url = kernel::single('invoice_electronic')->getApiEinvoiceUrl($rs_invoice,$_GET["type"]);
        if($einvoice_url){
            echo '<script>window.location.href="'.$einvoice_url.'";</script>';
            exit;
        }else{
            echo '<script>alert("预览失败");</script>';
            exit;
        }
    }
    
    //上传回流天猫前 开票操作类型选择页 这个是prepare接口用到 已放入上传天猫进度弹窗 先弃用着
//     function uploadTmall(){
//         if(!$_GET["id"]){
//             return false;
//         }
//         $this->pagedata["id"] = $_GET["id"];
//         $this->page('admin/upload_prepare.html');
//     }
    
    //淘宝系  上传天猫
    function doUploadTmall(){
        $step = intval($_GET['step']) ? intval($_GET['step']) : 1; //当前到第几步
        $total_step = intval($_GET["total_step"]); //全部步数
        $id = $_POST['invoice_id']; //发票记录主键id
        
        //获取invoice order信息
        $mdlInOrder = app::get('invoice')->model('order');
        $rs_invoice = $mdlInOrder->dump(array("id"=>$id));
        $rs_invoice["einvoice_type"] = "blue"; //prepare接口和回流天猫upload接口都用到
        $log_mes_type = "蓝票";
        $billing_type = "1";
        if(intval($rs_invoice["is_status"]) == 2 && intval($rs_invoice["sync"]) == 6){
            $rs_invoice["einvoice_type"] = "red";
            $log_mes_type ="红票";
            $billing_type = "2";
        }
        
        //获取invoice item明细
        $mdlInvoiceElIt = app::get('invoice')->model('order_electronic_items');
        $rs_invoice_item = $mdlInvoiceElIt->dump(array("id"=>$rs_invoice["id"],"billing_type"=>$billing_type));
        
        $opObj = app::get('ome')->model('operation_log');
        
        $result = array('status'=>'running');
        
        //更新对应记录明细表字段条件
        $mdlInOrderElIt = app::get('invoice')->model('order_electronic_items');
        $filter_arr = array("id"=>$id,"billing_type"=>1);
        if($rs_invoice["einvoice_type"] == "red"){
            $filter_arr["billing_type"] = 2;
        }
        
        //第一步 先打prepare接口
        if($step == 1){
            //判断是否更新天猫状态成功过
            if(intval($rs_invoice_item["update_tmall_status"]) == 1){
                //未成功更新
                $rs_invoice["invoice_action_type"] = intval($_POST["invoice_action_type"]); //prepare接口用到 注意当发票prepare接口已经成功调用后 此值为0 也不会再次调用prepare接口了
                $rs_invoice = kernel::single('invoice_electronic')->getEinvoiceSerialNo($rs_invoice,$billing_type);
                $einvoice_prepare_rs = kernel::single('invoice_event_trigger_einvoice')->einvoicePrepare($rs_invoice["shop_id"],$rs_invoice);
                if($einvoice_prepare_rs["rsp"] == "succ"){
                    //更新上传天猫状态字段 状态
                    $update_arr = array("update_tmall_status"=>2);
                    $mdlInOrderElIt->update($update_arr,$filter_arr);
                    $msg_prepare = $log_mes_type.'的天猫状态更新成功。';
                }else{
                    $msg_prepare = $log_mes_type.'的天猫状态更新失败。';
                    //获取返回的失败msg
                    if($einvoice_prepare_rs["rsp"] == "fail"){
                        $err_msg = @json_decode($einvoice_prepare_rs['err_msg'],true);
                        if($err_msg["error_response"]["sub_msg"]){
                            $msg_prepare .= "(".$err_msg["error_response"]["sub_msg"].")";
                        }
                    }
                    $prepare_fail = true;
                }
                //记录电子发票的天猫状态更新操作日志
                $opObj->write_log('einvoice_prepare_tmall@invoice', $id, $msg_prepare);
                //prepare失败
                if($prepare_fail){
                    $this->splash('error','',$msg_prepare.'请查看日志原因或重试。');
                }
            }else{
                //update_tmall_status字段为2 是已成功更新过了 直接走下一步
            }
        }
        
        //第二步  获取serial_no 打上传天猫接口
        if($step >= $total_step){
            //上传天猫必须通过打get接口来获取开票流水号serial_no
            $info_return_rs = kernel::single('invoice_event_trigger_einvoice')->getEinvoiceInfo($rs_invoice["shop_id"],$rs_invoice);
            $einvoice_data_arr = json_decode($info_return_rs["data"],true);
            $rs_invoice["serial_no"] = $einvoice_data_arr["serial_no"];
            
            //获取开票流水号serial_no成功
            if($rs_invoice["serial_no"]){
                //上传天猫接口
                $einvoice_upload_rs = kernel::single('invoice_event_trigger_einvoice')->uploadTmall($rs_invoice["shop_id"],$rs_invoice);
                if($einvoice_upload_rs["rsp"] == "succ"){
                    //上传天猫成功 更新发票明细表upload_tmall_status为2
                    $update_arr = array("upload_tmall_status"=>2);
                    $mdlInOrderElIt->update($update_arr,$filter_arr);
                    $msg_upload = $log_mes_type.'上传天猫成功。';
                }else{
                    $msg_upload = $log_mes_type.'上传天猫失败。';
                    //获取返回的失败msg
                    if($einvoice_upload_rs["rsp"] == "fail" && $einvoice_upload_rs["err_msg"]){
                        $msg_upload .= "(".$einvoice_upload_rs["err_msg"].")";
                    }
                    $upload_fail = true;
                }
            }else{
                $get_return_serial_no_fail = true;
                $msg_upload = $log_mes_type.'上传天猫失败。(获取开票流水号失败)';
            }
            
            //记录上传回流天猫操作日志
            $opObj->write_log('einvoice_upload_tmall@invoice', $id, $msg_upload);
            //上传失败 因为成功通过get接口获取开票流水号
            if($get_return_serial_no_fail){
                $this->splash('error','','获取开票流水号失败。请查看日志原因或重试。');
            }
            //上传失败
            if($upload_fail){
                $this->splash('error','','上传天猫失败。请查看日志原因或重试。');
            }
            //成功完成
            $result['status'] = 'complete';
            $result['data']['rate'] = '100';
        }else{
            //步骤中
            $result['data']['rate'] =  $step / $total_step * 100;
        }
        
        echo json_encode($result);exit;
    }
    
    //上传天猫进度弹窗
    public function uploadTmallExpire(){
        if($_GET["invoice_action_type"]){
            $this->pagedata["invoice_action_type"] = 1; //只有第一次开蓝票此值是1
        }
        //获取是否是否成功更新过天猫上的发票状态
        $mdlInvoiceElIt = app::get('invoice')->model('order_electronic_items');
        $rs_invoice_item = $mdlInvoiceElIt->dump(array("id"=>$_GET["id"],"billing_type"=>$_GET["billing_type"]));
        
        $this->pagedata['update_tmall_status'] = $rs_invoice_item["update_tmall_status"]; //非第一次开蓝票 判断如果update_tmall_status为1显示作废原因等选项
        $this->pagedata['invoice_id'] = $_GET["id"]; 
        $this->pagedata['total_step'] = 2; //二步  1.prepare接口  2.get接口获取开票流水号serial_no并上传天猫接口
        $this->display('admin/upload_tmall_expire.html');
    }
    
    //电子发票开票(蓝票或者红票)成功后获取发票开票结果查询
    public function getEinvoiceCreateResult(){
        $url = 'javascript:finderGroup["'.$_GET['finder_id'].'"].refresh();';
        $id = $_GET["id"];
        if(!$id){
            $this->splash('error',$url,'操作出错，不存在此条发票记录，请重新操作。');
        }
        $mdlInOrder = app::get('invoice')->model('order');
        $rs_invoice = $mdlInOrder->dump(array("id"=>$id),"*");
        $rs_invoice["billing_type"] = $_GET["billing_type"];
        $create_result = kernel::single('invoice_event_trigger_einvoice')->getEinvoiceCreateResult($rs_invoice["shop_id"],$rs_invoice);
        //先接口和矩阵联调通 后续需要再做业务逻辑处理
//         if($create_result["rsp"] == "succ"){
//             //目前ERP开票结果获取接口不管是获取成功create_success或者不成功create_failed rsp都是succ
//             $data = @json_decode($response['data'],true);
//             if(is_array($data) && $data["step"] == "2" && $data["invoice_result"][0]){
//                 $invoice_result_arr = $data["invoice_result"][0];
//                 if($invoice_result_arr["status"] == "create_failed"){
//                     $return_error_msg = $invoice_result_arr["biz_error_msg"];
//                 }
//             }
//         }
    }
    
}
